﻿/*
 * deneme icin yazilmis uygulama, Car isimli projeye eklenecek
 */
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Timers;

namespace EgeUniversity.SolarCarProject
{
	public class ClientClass
	{
		//Notify when connection status changed
		public event StatusChangedEventHandler ConnectionChanged;
		
		//Variables
		TcpClient myClient;
		Stream stream;
		byte[] databytes;
		bool isConnected;
		Timer timer;

		~ClientClass()
		{
			//Close while destructing
			if (myClient != null)
				myClient.Close();
		}

		public void Start()
		{//Start TCP/IP client
			myClient = new TcpClient();
			timer = new Timer();
			timer.Interval = 1000;
			timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
			try
			{
				//May be Local Broadcast IP ?
				myClient.Connect("192.168.1.10", 8001);
				OnConnectionChanged(ConnectionStatus.Connected);//rapor et
			}
			catch (Exception)
			{
				OnConnectionChanged(ConnectionStatus.Disconnected);
			}
		}
		
		void timer_Elapsed(object sender, ElapsedEventArgs e)
		{
			if (!isConnected)
				Start();
		}

		public void Send(string data)
		{//Send data
			try
			{
				if (isConnected)
				{
					stream = myClient.GetStream();

					ASCIIEncoding send= new ASCIIEncoding();
					databytes = send.GetBytes(data);

					stream.Write(databytes, 0, databytes.Length);
					timer.Stop();
				}
			}
			catch
			{
				OnConnectionChanged(ConnectionStatus.Disconnected);
			}
		}

		public virtual void OnConnectionChanged(ConnectionStatus e)
		{
			isConnected = (e == ConnectionStatus.Connected);
			if (!isConnected && !timer.Enabled)
				timer.Start();
			if (ConnectionChanged != null)
				ConnectionChanged(e);
		}
	}
}